<template>
  <div class="main">
    <breadcrumb/>
    <el-card>
      <el-row :gutter="10">
        <el-col :span="5">
          <el-input placeholder="请输入搜索关键字" v-model="queryInfo.query" clearable>
            <el-button slot="append" icon="el-icon-search" @click="getUsers"></el-button>
          </el-input>
        </el-col>
        <el-col :span="5">
          <el-button type="primary" @click="addUserDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <el-table
        :data="userList"
        style="width: 100%"
        stripe
        border
      >
        <el-table-column
          prop="id"
          label="#"
          type="index"
          header-align="center"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="username"
          label="用户名"
          header-align="center"
          align="center">
        </el-table-column>
        <el-table-column
          prop="role_name"
          label="角色名称"
          header-align="center"
          align="center">
        </el-table-column>
        <el-table-column
          prop="mobile"
          label="手机号"
          header-align="center"
          align="center">
        </el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
          header-align="center"
          align="center">
        </el-table-column>
        <el-table-column
          prop="mg_state"
          label="状态"
          header-align="center"
          align="center"
        >
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="modifyUserState(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="200"
          header-align="center"
          align="center"
        >
          <template slot-scope="scope">
            <el-button type="primary" class="el-icon-edit" size="mini" @click="openModifyDialog(scope.row)"></el-button>
            <el-button type="danger" class="el-icon-delete" size="mini" @click="deleteUser(scope.row.id)"></el-button>
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" class="el-icon-setting" size="mini"
                         @click="openAssignRoleDialog(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :page-sizes="[1, 2, 4, 10]"
        :page-size="queryInfo.pagesize"
        :page-count="pageCount"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :current-page="queryInfo.pagenum"
        @size-change="handlerSizeChange"
        @current-change="handlerCurrentChange"
      >
      </el-pagination>
    </el-card>

    <!--新增用户弹窗-->
    <el-dialog
      title="新增用户"
      :visible.sync="addUserDialogVisible"
      width="50%"
      @close="handleAddUserDialogClose"
      :close-on-click-modal="false"
    >
      <el-form :model="addUserForm" :rules="addUserFormRules" ref="addUserFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPassword">
          <el-input type="password" v-model="addUserForm.checkPassword"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!--修改用户信息弹窗-->
    <el-dialog
      title="新增用户"
      :visible.sync="modifyUserDialogVisible"
      width="50%"
      :close-on-click-modal="false"
    >
      <el-form :model="modifyForm" :rules="modifyFormRules" ref="modifyFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="modifyForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="modifyForm.mobile"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="modifyForm.email"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="modifyUserDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="modifyUser">确认修改</el-button>
       </span>
    </el-dialog>

    <!--分配角色弹窗-->
    <el-dialog
      title="分配角色"
      :visible.sync="assignRoleDialogVisible"
      width="50%"
      :close-on-click-modal="false"
      @close="selectedRoleId = ''"
    >
      <p>用户名：{{selectedUser.username}}</p>
      <p>当前角色：{{selectedUser.role_name}}</p>
      <p>
        可选角色：
        <el-select v-model="selectedRoleId" placeholder="请选择">
          <el-option
            v-for="role in roles"
            :key="role.id"
            :label="role.roleName"
            :value="role.id">
          </el-option>
        </el-select>
      </p>
      <span slot="footer" class="dialog-footer">
          <el-button @click="assignRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="modifyUserRole">保存</el-button>
       </span>
    </el-dialog>
  </div>
</template>

<script>
import Breadcrumb from './../../components/Breadcrumb'
import { addUser, deleteUserById, getUserById, getUserList, modifyUserInfo, modifyUserState, modifyUserRole } from '@/api/user/user'
import { getRoles } from '@/api/right/roles'

export default {
  name: 'Users',
  components: { Breadcrumb },
  data () {
    /* 自定义校验规则 */
    const checkPassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.addUserForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    const checkPhone = (rule, value, callback) => {
      if (value !== '') {
        if (!/^1(3|4|5|6|7|8)\d{9}$/.test(value)) {
          callback(new Error('输入正确的手机号!'))
        }
      }
      callback()
    }
    const checkEmail = (rule, value, callback) => {
      if (value !== '') {
        if (!/^\w+@[a-z0-9]+\.[a-z]{2,4}$/.test(value)) {
          callback(new Error('请输入正确邮箱!'))
        }
      }
      callback()
    }
    return {
      keyword: '',
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userList: [],
      total: 0,
      pageCount: 0,
      addUserDialogVisible: false,
      modifyUserDialogVisible: false,
      assignRoleDialogVisible: false,
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
        checkPassword: ''
      },
      addUserFormRules: {
        username: [
          { required: true, message: '用户名不能为空', trigger: 'blur' },
          { min: 2, message: '用户名不能少于2位', trigger: 'blur' },
          { max: 15, message: '用户名不能大于15位', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 6, message: '密码不能少于6位', trigger: 'blur' },
          { max: 20, message: '密码不能大于20位', trigger: 'blur' }
        ],
        checkPassword: [
          { validator: checkPassword, trigger: 'blur' }
        ],
        mobile: [
          { validator: checkPhone, trigger: 'blur' }
        ],
        email: [
          { validator: checkEmail, trigger: 'blur' }
        ]
      },
      modifyFormRules: {
        mobile: [
          { validator: checkPhone, trigger: 'blur' }
        ],
        email: [
          { validator: checkEmail, trigger: 'blur' }
        ]
      },
      modifyForm: {},
      selectedUser: {},
      selectedRoleId: '',
      roles: []
    }
  },
  created () {
    this.getUsers()
  },

  methods: {
    // 修改角色权限
    async modifyUserRole () {
      const { data: res } = await modifyUserRole(this.selectedUser.id, this.selectedRoleId)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      await this.getUsers()
      this.assignRoleDialogVisible = false
    },

    // 点击分配角色弹窗
    async openAssignRoleDialog (user) {
      this.selectedUser = user
      const { data: res } = await getRoles()
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.roles = res.data
      this.assignRoleDialogVisible = true
    },

    // 删除用户
    async deleteUser (id) {
      const r = await this.$confirm('确定要删除用户？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (r !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await deleteUserById(id)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getUsers()
    },

    // 修改用户信息
    modifyUser () {
      this.$refs.modifyFormRef.validate(async valid => {
        if (!valid) return
        const r = await this.$confirm('确定要保存修改？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        if (r !== 'confirm') {
          return this.$message.info('已取消修改')
        }
        const { data: res } = await modifyUserInfo(this.modifyForm)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success('修改信息成功')
        await this.getUsers()
        this.modifyUserDialogVisible = false
      })
    },

    // 打开修改弹窗
    async openModifyDialog (row) {
      const { data: res } = await getUserById(row.id)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.modifyForm = res.data
      this.modifyUserDialogVisible = true
    },

    // 新增用户
    addUser () {
      this.$refs.addUserFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await addUser(this.addUserForm)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        await this.getUsers()
        this.addUserDialogVisible = false
      })
    },

    // 新增用户弹窗关闭事件
    handleAddUserDialogClose () {
      this.$refs.addUserFormRef.resetFields()
    },

    // 修改用户状态
    async modifyUserState (row) {
      const { data: res } = await modifyUserState(row.id, row.state)
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
        await this.getUsers()
        return
      }
      this.$message.success(res.meta.msg)
    },

    // 改变分页条页面大小
    handlerSizeChange (pageSize) {
      this.queryInfo.pagesize = pageSize
      this.getUsers()
    },

    // 改变分页条当前页
    handlerCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getUsers()
    },

    // 获取用户数据
    async getUsers () {
      const { data: res } = await getUserList(this.queryInfo)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.userList = res.data.users
      this.total = res.data.total
      this.pageCount = this.total / res.data.pagenum
    }
  }
}
</script>
<style lang="less" scoped>
  @import "./index";
</style>
